<template>
    <div id="user-verify">
        <el-form ref="phoneFormRef" style="max-width: 600px;margin: 0 auto;" :model="phoneForm" :rules="rules"
            label-width="auto" scroll-to-error="true">
            <el-form-item label="手机号" prop="phone">
                <el-row style="width: 100%;">
                    <el-input v-model.number="phoneForm.phone"></el-input>
                </el-row>
            </el-form-item>
            <el-form-item label="短信验证码" prop="verify_code">
                <el-row style="width: 100%;">
                    <el-col :span="14">
                        <el-input v-model="phoneForm.verify_code"/>
                    </el-col>
                    <el-col :span="6" :offset="2">
                        <el-button @click="sendCode(phoneFormRef)">发送验证码</el-button>
                    </el-col>
                </el-row>
            </el-form-item>
            <el-form-item>
                <el-button :disabled='buttonStatus' @click="verifyCode(phoneForm.verify_code)">验证</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { message } from '@/utils/commonMessage/common.js'
import variable from '@/utils/properties.yaml'
import router from '@/router'

//数据类型
interface PhoneForm {
    region?: string,
    phone?: number,
    verify_code?: number,
}

const phoneFormRef = ref<FormInstance>()
//具体初始的值
const phoneForm = reactive<PhoneForm>({
    // region: '中国+86',
})
const buttonStatus = ref(true)
//具体的规则
const rules = reactive<FormRules<PhoneForm>>({
    region: [
        { required: true, message: '请选择地区编码', },
    ],
    phone: [
        { required: true, message: '请输入电话号码以获取验证码', trigger: 'blur' },
        { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号', trigger: 'blur' },
        { type: 'number', message: '电话号码应为数字', trigger: 'blur' },
    ],
    verify_code: [
        {
            required: true,
            message: '请输入验证码',
        },
    ]
})

//发送和验证函数
function sendCode(phoneFormRef: FormInstance | undefined) {
    if (!phoneFormRef)
        return
    phoneFormRef.validateField('phone', (valid) => {
        if (valid) {
            message('发送验证码成功', 'success')
            buttonStatus.value = false
            //修改按钮todo
        }
    })
}

function verifyCode(code: number) {
    if (code == variable.register.verify_code) {
        message('验证成功', 'success')
        router.push('/user-register/register2')
    } else {
        message('验证码有误', 'error')
    }
}
</script>

<style>
#user-verify {
    width: 85%;
    margin: auto 0;
}
</style>
